/*
文件名称: welcome.js
完整路径: frontend/static/js/welcome.js
功能说明: 中医适宜技术防控青少年近视系统宣传页面交互逻辑
版本: 2.0.0
最后修改: 2025-01-27
使用说明: 依赖 Chart.js 和 chart_api.py 返回的数据格式
*/

document.addEventListener("DOMContentLoaded", function () {
  // 初始化所有功能
  initModalHandlers();
  initFormHandlers();
  initWelcomeCharts();
  initScrollAnimations();
  initStatisticsRefresh(); // 添加统计数据刷新功能
});

/**
 * 初始化模态框处理器
 */
function initModalHandlers() {
  const loginButton = document.getElementById("login-button");
  const registerButton = document.getElementById("register-button");
  const loginForm = document.getElementById("login-form");
  const registerForm = document.getElementById("register-form");
  const closeLogin = document.getElementById("close-login");
  const closeRegister = document.getElementById("close-register");
  const cancelLogin = document.getElementById("cancel-login");
  const cancelRegister = document.getElementById("cancel-register");

  // 登录按钮点击事件
  if (loginButton && loginForm) {
    loginButton.addEventListener("click", function () {
      clearFormInputs("login");
      loginForm.style.display = "flex";
      if (registerForm) registerForm.style.display = "none";
    });
  }

  // 注册按钮点击事件
  if (registerButton && registerForm) {
    registerButton.addEventListener("click", function () {
      clearFormInputs("register");
      registerForm.style.display = "flex";
      if (loginForm) loginForm.style.display = "none";
    });
  }

  // 关闭按钮事件
  if (closeLogin && loginForm) {
    closeLogin.addEventListener("click", function () {
      loginForm.style.display = "none";
    });
  }

  if (closeRegister && registerForm) {
    closeRegister.addEventListener("click", function () {
      registerForm.style.display = "none";
    });
  }

  // 取消按钮事件
  if (cancelLogin && loginForm) {
    cancelLogin.addEventListener("click", function () {
      clearFormInputs("login");
      loginForm.style.display = "none";
    });
  }

  if (cancelRegister && registerForm) {
    cancelRegister.addEventListener("click", function () {
      clearFormInputs("register");
      registerForm.style.display = "none";
    });
  }

  // 点击模态框外部关闭
  window.addEventListener("click", function (event) {
    if (event.target === loginForm) {
      loginForm.style.display = "none";
    }
    if (event.target === registerForm) {
      registerForm.style.display = "none";
    }
  });
}

/**
 * 初始化表单处理器
 */
function initFormHandlers() {
  const loginForm = document.querySelector(".login-form");
  const registerForm = document.querySelector(".register-form");
  const submitLogin = document.getElementById("submit-login");
  const submitRegister = document.getElementById("submit-register");

  // 登录表单提交
  if (loginForm && submitLogin) {
    loginForm.addEventListener("submit", function (e) {
      e.preventDefault();
      handleLogin();
    });
  }

  // 注册表单提交
  if (registerForm && submitRegister) {
    registerForm.addEventListener("submit", function (e) {
      e.preventDefault();
      handleRegister();
    });
  }
}

/**
 * 处理登录逻辑
 */
function handleLogin() {
  const username = document.getElementById("username").value.trim();
  const password = document.getElementById("password").value;

  if (!username || !password) {
    showAlert("请填写完整的登录信息", "error");
    return;
  }

  // 显示加载状态
  const submitBtn = document.getElementById("submit-login");
  const originalText = submitBtn.innerHTML;
  submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 登录中...';
  submitBtn.disabled = true;

  fetch("/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password })
  })
  .then(res => res.json().then(data => ({ status: res.status, data })))
  .then(({ status, data }) => {
    // 数据库不可用：后端返回 503 或 data.error == 'db_connect_failed'
    if (status === 503 || data.error === 'db_connect_failed') {
      showAlert(data.message || '系统暂时不可用，请稍后再试', 'error');
      return;
    }
    if (status === 200 && data.access_token) {
      // 存储token
      localStorage.setItem('access_token', data.access_token);
      // 记录登录时间，用于权限控制延迟检查
      localStorage.setItem('login_time', Date.now().toString());
      document.cookie = "access_token=" + data.access_token + "; path=/";
      
      showAlert("登录成功，正在跳转...", "success");
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        window.location.href = "/index";
      }, 1000);
    } else {
      // 优先展示后端 message（服务层统一使用 message 字段）
      const msg = data.message || data.msg || '登录失败，请检查用户名和密码';
      showAlert(msg, 'error');
    }
  })
  .catch(err => {
    showAlert("登录请求失败: " + err.message, "error");
  })
  .finally(() => {
    // 恢复按钮状态
    submitBtn.innerHTML = originalText;
    submitBtn.disabled = false;
  });
}

/**
 * 处理注册逻辑
 */
function handleRegister() {
  const username = document.getElementById("register-username").value.trim();
  const password = document.getElementById("register-password").value;
  const password2 = document.getElementById("register-password2").value;

  if (!username || !password || !password2) {
    showAlert("请填写完整的注册信息", "error");
    return;
  }

  if (password !== password2) {
    showAlert("两次输入的密码不一致", "error");
    return;
  }

  if (password.length < 6) {
    showAlert("密码长度至少6位", "error");
    return;
  }

  // 显示加载状态
  const submitBtn = document.getElementById("submit-register");
  const originalText = submitBtn.innerHTML;
  submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 注册中...';
  submitBtn.disabled = true;

  fetch("/api/auth/register", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password })
  })
  .then(res => res.json().then(data => ({ status: res.status, data })))
  .then(({ status, data }) => {
    if (status === 200 && data.success) {
      showAlert("注册成功，请登录", "success");
      // 切换到登录表单
      document.getElementById("register-form").style.display = "none";
      document.getElementById("login-form").style.display = "flex";
      clearFormInputs("register");
    } else {
      showAlert(data.msg || "注册失败，请稍后重试", "error");
    }
  })
  .catch(err => {
    showAlert("注册请求失败: " + err.message, "error");
  })
  .finally(() => {
    // 恢复按钮状态
    submitBtn.innerHTML = originalText;
    submitBtn.disabled = false;
  });
}

/**
 * 清空表单输入
 */
function clearFormInputs(formType) {
  if (formType === "login") {
    document.getElementById("username").value = "";
    document.getElementById("password").value = "";
  } else if (formType === "register") {
    document.getElementById("register-username").value = "";
    document.getElementById("register-password").value = "";
    document.getElementById("register-password2").value = "";
  }
}

/**
 * 显示提示消息
 */
function showAlert(message, type = "info") {
  // 移除现有的提示
  const existingAlert = document.querySelector(".alert");
  if (existingAlert) {
    existingAlert.remove();
  }

  // 创建新的提示
  const alert = document.createElement("div");
  alert.className = `alert alert-${type}`;
  
  const icon = type === "success" ? "bi-check-circle" : 
               type === "error" ? "bi-exclamation-triangle" : 
               "bi-info-circle";
  
  alert.innerHTML = `
    <i class="bi ${icon}"></i>
    <span>${message}</span>
  `;

  document.body.appendChild(alert);

  // 3秒后自动移除
  setTimeout(() => {
    if (alert.parentNode) {
      alert.remove();
    }
  }, 3000);
}

/**
 * 初始化欢迎页面图表
 */
function initWelcomeCharts() {
  // 使用新的Dashboard API获取图表数据和统计数据
  fetch("/api/dashboard/overview?page=welcome", {
    method: "GET",
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      // 更新统计数据卡片
      if (data.data.statistics) {
        updateStatisticsCards(data.data.statistics);
      }
      
      // 渲染图表
      if (data.data.charts) {
        // 渲染左眼视力趋势图表
        if (data.data.charts.left_eye_trend) {
          renderWelcomeChart("leftEyeChart", data.data.charts.left_eye_trend, "左眼视力趋势");
        }
        
        // 渲染右眼视力趋势图表
        if (data.data.charts.right_eye_trend) {
          renderWelcomeChart("rightEyeChart", data.data.charts.right_eye_trend, "右眼视力趋势");
        }
      }
    } else {
      console.warn(`Dashboard数据获取失败: ${data.message}`);
      // 使用演示数据
      renderDemoChart("leftEyeChart", "左眼视力趋势");
      renderDemoChart("rightEyeChart", "右眼视力趋势");
    }
  })
  .catch(error => {
    console.error(`Dashboard请求失败: ${error}`);
    // 使用演示数据
    renderDemoChart("leftEyeChart", "左眼视力趋势");
    renderDemoChart("rightEyeChart", "右眼视力趋势");
  });
}

/**
 * 更新统计数据卡片
 * @param {Object} statistics - 统计数据对象
 */
function updateStatisticsCards(statistics) {
  // 添加动画效果的数字递增
  animateNumber('total-students', statistics.total_students || 0);
  animateNumber('total-vision', statistics.total_vision || 0);
  animateNumber('total-intervention', statistics.total_intervention || 0);
  animateNumberWithPercent('improvement-rate', statistics.improvement_rate || 0);
}

/**
 * 数字递增动画效果
 * @param {string} elementId - 元素ID
 * @param {number} targetValue - 目标数值
 */
function animateNumber(elementId, targetValue) {
  const element = document.getElementById(elementId);
  if (!element) return;
  
  const startValue = 0;
  const duration = 2000; // 2秒动画
  const startTime = performance.now();
  
  function update(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // 使用缓动函数让动画更自然
    const easedProgress = 1 - Math.pow(1 - progress, 3);
    const currentValue = Math.floor(startValue + (targetValue - startValue) * easedProgress);
    
    element.textContent = currentValue;
    
    if (progress < 1) {
      requestAnimationFrame(update);
    }
  }
  
  requestAnimationFrame(update);
}

/**
 * 百分比数字递增动画效果
 * @param {string} elementId - 元素ID
 * @param {number} targetValue - 目标数值
 */
function animateNumberWithPercent(elementId, targetValue) {
  const element = document.getElementById(elementId);
  if (!element) return;
  
  const startValue = 0;
  const duration = 2000; // 2秒动画
  const startTime = performance.now();
  
  function update(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    
    // 使用缓动函数让动画更自然
    const easedProgress = 1 - Math.pow(1 - progress, 3);
    const currentValue = (startValue + (targetValue - startValue) * easedProgress).toFixed(1);
    
    element.textContent = currentValue + '%';
    
    if (progress < 1) {
      requestAnimationFrame(update);
    }
  }
  
  requestAnimationFrame(update);
}

/**
 * 获取图表数据（保留兼容性，已弃用）
 */
function fetchChartData(params, canvasId, title) {
  // 这个函数保留用于兼容性，但建议使用新的Dashboard API
  fetch("/api/chart/analysis", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + (localStorage.getItem('access_token') || '')
    },
    body: JSON.stringify(params)
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      renderWelcomeChart(canvasId, data.data, title);
    } else {
      console.warn(`图表数据获取失败: ${data.message}`);
      renderDemoChart(canvasId, title);
    }
  })
  .catch(error => {
    console.error(`图表请求失败: ${error}`);
    renderDemoChart(canvasId, title);
  });
}

/**
 * 渲染欢迎页面图表
 */
function renderWelcomeChart(canvasId, data, title) {
  const canvas = document.getElementById(canvasId);
  if (!canvas) return;

  const ctx = canvas.getContext('2d');
  
  // 销毁现有图表
  if (window[canvasId + 'Chart']) {
    window[canvasId + 'Chart'].destroy();
  }

  const chartData = {
    labels: data.labels || ['1月', '2月', '3月', '4月', '5月', '6月'],
    datasets: data.datasets || [{
      label: title,
      data: [4.8, 4.9, 5.0, 4.9, 5.1, 5.2],
      borderColor: '#667eea',
      backgroundColor: 'rgba(102, 126, 234, 0.1)',
      borderWidth: 3,
      fill: true,
      tension: 0.4
    }]
  };

  window[canvasId + 'Chart'] = new Chart(ctx, {
    type: 'line',
    data: chartData,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: title,
          color: '#333',
          font: {
            size: 16,
            weight: 'bold'
          }
        },
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: false,
          min: 4.0,
          max: 5.5,
          ticks: {
            color: '#666'
          },
          grid: {
            color: 'rgba(0,0,0,0.1)'
          }
        },
        x: {
          ticks: {
            color: '#666'
          },
          grid: {
            color: 'rgba(0,0,0,0.1)'
          }
        }
      },
      elements: {
        point: {
          radius: 6,
          hoverRadius: 8,
          backgroundColor: '#667eea'
        }
      }
    }
  });
}

/**
 * 渲染演示图表（当数据获取失败时）
 */
function renderDemoChart(canvasId, title) {
  const canvas = document.getElementById(canvasId);
  if (!canvas) return;

  const ctx = canvas.getContext('2d');
  
  // 销毁现有图表
  if (window[canvasId + 'Chart']) {
    window[canvasId + 'Chart'].destroy();
  }

  // 生成演示数据
  const demoData = {
    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
    datasets: [{
      label: title,
      data: [4.8, 4.9, 5.0, 4.9, 5.1, 5.2],
      borderColor: '#667eea',
      backgroundColor: 'rgba(102, 126, 234, 0.1)',
      borderWidth: 3,
      fill: true,
      tension: 0.4
    }]
  };

  window[canvasId + 'Chart'] = new Chart(ctx, {
    type: 'line',
    data: demoData,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: title + ' (演示数据)',
          color: '#666',
          font: {
            size: 14,
            weight: 'normal'
          }
        },
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: false,
          min: 4.0,
          max: 5.5,
          ticks: {
            color: '#999'
          },
          grid: {
            color: 'rgba(0,0,0,0.05)'
          }
        },
        x: {
          ticks: {
            color: '#999'
          },
          grid: {
            color: 'rgba(0,0,0,0.05)'
          }
        }
      },
      elements: {
        point: {
          radius: 4,
          hoverRadius: 6,
          backgroundColor: '#999'
        }
      }
    }
  });
}

/**
 * 初始化滚动动画
 */
function initScrollAnimations() {
  // 监听滚动事件，为元素添加动画
  const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.style.opacity = '1';
        entry.target.style.transform = 'translateY(0)';
      }
    });
  }, observerOptions);

  // 观察需要动画的元素
  const animatedElements = document.querySelectorAll('.feature-card, .screening-card, .technique-method, .technique-mechanism');
  animatedElements.forEach(el => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(30px)';
    el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    observer.observe(el);
  });
}

/**
 * 平滑滚动到指定元素
 */
function scrollToElement(elementId) {
  const element = document.getElementById(elementId);
  if (element) {
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
}

/**
 * 更新统计数据（如果需要动态更新）
 */
function updateStats() {
  // 这里可以添加动态更新统计数据的逻辑
  // 例如从后端API获取最新的统计数据
  console.log('统计数据更新功能待实现');
}

/**
 * 初始化统计数据刷新功能
 */
function initStatisticsRefresh() {
  // 统计数据刷新功能
  console.log('统计数据刷新功能已初始化');
  
  // 可以在这里添加定时刷新逻辑
  // setInterval(updateStats, 30000); // 每30秒刷新一次
}